// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://s.taobao.com/*
// @match        https://detail.tmall.com/*
// @match        https://detail.tmall.hk/*
// @match        https://item.taobao.com/*
// @grant        none
// @require      http://libs.baidu.com/jquery/2.0.0/jquery.min.js
// @run-at       document-start
// ==/UserScript==

;(function () {
    'use strict';

    const gls = (function () {
        const _vars = {
            glsHost: 'https://lyh294847.gitee.io/tampermonkey/localStorage.html',
            frameId: 'fr_xx_vv',
            tempCb: null
        };
        return {
            init() {
                $(`<iframe id="${_vars.frameId}" src="${_vars.glsHost}"></iframe>`).prependTo('body');
                window.addEventListener('message', function (e) {
                    if (_vars.tempCb) {
                        _vars.tempCb(e.data)
                    }
                })
            },
            setGlobalLocalStorage(key, value) {
                $(`#${_vars.frameId}`)[0].contentWindow.postMessage(`set:${key}:${value}`, '*');
            },
            getGlobalLocalStorage(key, callback) {
                _vars.tempCb = callback
                $(`#${_vars.frameId}`)[0].contentWindow.postMessage(`get:${key}`, '*');
            },
            removeGlobalLocalStorage(key) {
                $(`#${_vars.frameId}`)[0].contentWindow.postMessage(`remove:${key}`, '*');
            }
        }
    })();

    const ls = (function () {
        return {
            init() {
                $(`<div onclick="localStorage.clear();alert('清空成功');">清空localStorage</div>`).prependTo('body');
            },
            setLocalStorage(key, value) {
                localStorage.setItem(key, value);
            },
            getLocalStorage(key) {
                return localStorage.getItem(key);
            },
            removeLocalStorage(key) {
                localStorage.removeItem(key);
            }
        }
    })();

    const detailingGls = 'detailing',//正在查看详情key标识
        targetGoodGls = 'targetGood',//已找到目标商品key标识
        taobaoSearchUrl = 's.taobao.com', //淘宝搜索url
        compareMaxNum = 2,//最大比价次数
        pageMaxNum = 5;//最大访问页数


    let q = 'nike',//搜索关键字
        tgStoreName = 'nike官方旗舰店',//目标商家名
        tgGoodName = '耐克官方LEBRON XVII EP男子篮球鞋 BQ3178';//目标商品名（模糊匹配）


    $(function () {
        gls.init();
    });

    $(window).load(function () {
        const url = location.href;
        if (url.includes(taobaoSearchUrl)) {
            fun1();
        } else {
            fun2();
        }
    });

    function fun1() {
        const $q = $('#q');
        if (!$q.val()) {
            $q.val(q);
            $('#J_SearchForm > button').click();
        } else {
            gls.removeGlobalLocalStorage(detailingGls);
            let compareNum = compareMaxNum;
            let pageNum = pageMaxNum;


            function promise0() {
                return new Promise(function (resolve, resject) {
                    const exclude = [];
                    const goods = getGoodList();
                    let targetGood;//目标商品
                    for (let j = 0; j < goods.length; j++) {
                        const good = goods[j];
                        if (isTargetGood(good)) {
                            alert('本页存在目标');
                            exclude.push(j);
                            targetGood = good;
                        }
                    }
                    let compareNumTemp = compareNum <= 0 ? 0 : (targetGood ? compareNum : 1);
                    const waitDetail = setInterval(() => {
                        gls.getGlobalLocalStorage(detailingGls, v => {
                            if (v) {
                                console.log('正在详情中');
                            } else {
                                if (compareNumTemp > 0) {
                                    const randIndex = randomIntByExclude(0, goods.length, exclude);
                                    if (!randIndex) {
                                        console.log('clearInterval success:waitDetail');
                                        clearInterval(waitDetail);
                                    } else {
                                        exclude.push(randIndex);
                                        const compareGood = goods[randIndex];
                                        $('#' + compareGood.detailClickId)[0].click();
                                        gls.setGlobalLocalStorage(detailingGls, 1);
                                        compareNum--;
                                        compareNumTemp--;
                                    }
                                } else {
                                    console.log('clearInterval success:waitDetail');
                                    clearInterval(waitDetail);
                                    if (targetGood) {
                                        $('#' + targetGood.detailClickId)[0].click();
                                    }
                                    resolve();
                                }
                            }
                        })
                    }, 3000);
                })
            }

            function loopArray(fun) {
                fun().then(() => {
                    pageNum--;
                    if (pageNum > 0 && compareNum > 0) {
                        $('.J_Ajax.num.icon-tag[trace="srp_bottom_pagedown"]')[0].click();
                        sleep(3000).then(() => {
                            loopArray(promise0);
                        })
                    }
                })
            }

            loopArray(promise0);

        }

    }

    function fun2() {
        let height = document.body.scrollHeight;
        let i = 0;
        sleep(1000).then(() => {
            const storeName = $('.shopLink').text().trim();
            const goodName = $('.tb-detail-hd > h1').text().trim();
            const good = new Good(storeName, goodName)
            if (isTargetGood(good)) {
                alert('这是目标');
            } else {
                scrollBottom(() => {
                    gls.removeGlobalLocalStorage(detailingGls);
                    window.close();
                })
            }
        })
    }

    //滑动到底部
    function scrollBottom(callback) {
        let scrollMove = setInterval(function () {
            if (i >= height - 500) {
                console.log('scorll over');
                clearInterval(scrollMove);
                callback();
            } else {
                if (document.body.scrollHeight > height) {
                    height = document.body.scrollHeight;
                }
                i += randomInt(1, 100);
                window.scrollTo(0, i);
            }
        }, 10);//数值越大，滚动速度越慢
    }

    //睡眠 毫秒
    function sleep(ms) {
        return new Promise(resolve =>
            setTimeout(resolve, ms)
        )
    }

    /*生成随机整数
    *@param{Integer}min 下限（包含）
    *@param{Integer}max 上限（不包含）
    *@param{Array}exclude 排除数字
    */
    function randomIntByExclude(min, max, exclude) {
        const randBase = [];
        for (let i = min; i < max; i++) {
            const index = exclude.indexOf(i);
            if (index > -1) {
                exclude.splice(index, 1)
                continue;
            }
            randBase.push(i);
        }
        const randBaseLen = randBase.length;
        if (randBaseLen == 0) {
            return null;
        }
        return parseInt(Math.random() * randBaseLen);
    }

    /*生成随机整数
    *@param{Integer}min 下限（包含）
    *@param{Integer}max 上限（不包含）
    */
    function randomInt(min, max) {
        return parseInt(Math.random() * (max - min) + min);
    }

    /*商品对象
     *@param{String}storeName 商家名
     *@param{String}goodName 商品名
     *@param{String}detailClickId 点击进去详情a标签id，便于立即定位
    */
    function Good(storeName, goodName, detailClickId) {
        this.storeName = storeName;
        this.goodName = goodName;
        this.detailClickId = detailClickId;
    }

    /*
     *是否目标商品
     * @param{Good}good 商品
     */
    function isTargetGood(good) {
        return good.storeName == tgStoreName && good.goodName.indexOf(tgGoodName) > -1;
    }

    /*
     *获取当前页面所有商品
     */
    function getGoodList() {
        const $goodList = $('#mainsrp-itemlist .J_MouseEneterLeave.J_IconMoreNew');
        const goods = [];
        $goodList.each(function () {
            const $item = $(this).find('.J_ClickStat');
            const detailClickId = $item.attr('id');
            const goodName = $item.text().trim();
            const storeName = $(this).find('.shopname.J_MouseEneterLeave.J_ShopInfo > span:nth-child(2)').text().trim();
            const good = new Good(storeName, goodName, detailClickId);
            goods.push(good);
        });
        return goods;
    }

})();